package com.basker.pisces.springcloud.signature;

import com.basker.pisces.service.exception.SignatureException;
import com.basker.pisces.service.exception.SignatureNotMatchException;
import com.basker.pisces.service.exception.SignatureTimeoutException;

/**
 * 签名校验器
 *
 * @author hangwen
 */
public class SignatureValidator {

    /**
     * 签名校验，如果不匹配则会抛出异常
     *
     * @param currentSignature 服务端生成的签名
     * @param postSignature    提交的签名
     * @param timeoutMinutes   签名的超时分钟数,<=0则表示不考虑超时
     * @throws SignatureValidationException
     */
    public void validate(Signature currentSignature, Signature postSignature, int timeoutMinutes)
            throws SignatureException {
        if (timeoutMinutes > 0) {
            long expireTimestamp = postSignature.getTimestamp() + timeoutMinutes * 60 * 1000;

            if (System.currentTimeMillis() > expireTimestamp) {
                throw new SignatureTimeoutException();
            }
        }

        if (!currentSignature.getDigest().equals(postSignature.getDigest())) {
            throw new SignatureNotMatchException();
        }

    }

}
